import UIKit
import Flutter
import StoreKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      
      GeneratedPluginRegistrant.register(with: self)
      
      let rsp = super.application(application, didFinishLaunchingWithOptions: launchOptions)
      
      self.initAdSdk()

      let controller = self.window.rootViewController as! FlutterViewController
      let navigationController = UINavigationController(rootViewController: controller)
      navigationController.isNavigationBarHidden = true
      navigationController.navigationBar.isTranslucent = true

      window.rootViewController = navigationController;

      let adChannel = FlutterMethodChannel(name:"native_controller_channel", binaryMessenger: controller.binaryMessenger)

      adChannel.setMethodCallHandler { (call:FlutterMethodCall, result:@escaping FlutterResult) in
                  if (call.method == "showSplashAd") {
                      self.showSplashAd()
                      result(true)
                  } else if (call.method == "showInterstitialAd") {
                      self.showInterstitialAd()
                      result(true)
                  }
              }

      self.showSplashAd()
    return rsp
  }
    
    func initAdSdk() {
        CXHAdSDK.setRequestDomain("http://ad.bwton.com")
        // TODO 替换成自己的APPID
        CXHAdSDK.initWithAppId("310641") { error in
            NSLog("BWTAD->initWithAppIdFinish...")
        }
    }

    // 展示开屏广告
    func showSplashAd() {
        NSLog("BWTAD->showSplashAd...")

        let navigationController = window.rootViewController as! UINavigationController
        navigationController.pushViewController(CXHSplashViewController(), animated: false)
    }

    // 展示插屏广告
    func showInterstitialAd() {
        NSLog("BWTAD->showInterstitialAd...")
        presentController(controller: CXHInterstitialAdController())
    }

    func presentController(controller:UIViewController) {
        controller.modalPresentationStyle = UIModalPresentationStyle.custom;
        controller.view.backgroundColor = UIColor.clear
        self.window.rootViewController?.present(controller, animated: false, completion: nil)
    }
}
